package slhs.tempo.scriptGenerator;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelExtractor {
    private String path = null;
    private Sheet sheet;

    public ExcelExtractor(String path) {
	this.path = path;
    }

    public boolean open(int sheetNumber) {
	boolean success = false;
	try {
	    InputStream inp = new FileInputStream(path);
	    try {
		org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
		sheet = wb.getSheetAt(sheetNumber);

	    } catch (org.apache.poi.poifs.filesystem.OfficeXmlFileException e) {
		XSSFWorkbook wb = new XSSFWorkbook(path);
		SXSSFWorkbook swb = new SXSSFWorkbook(wb);
		sheet = swb.getSheetAt(sheetNumber);

	    }

	    success = true;
	} catch (Exception e) {
	    success = false;
	    e.printStackTrace();
	}
	return success;
    }

    public boolean open() {
	return open(0);
    }

    public Iterator<Row> getRowIterator() {
	if (sheet != null)
	    return sheet.rowIterator();
	else
	    return null;
    }
}
